import 'package:dio/dio.dart';
import 'package:flutter/widgets.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:libflutter/Contact.dart';
import 'package:libflutter/net/RDOnError.dart';
import 'package:libflutter/net/RDResponse.dart';
import 'package:libflutter/net/RDService.dart';

///地址数据
class RDApi {
  final RDSerivce _httpService = RDSerivce();

  final String host;

  final String version;

  final bool debug;

  int? _orgId;

  int? _projectId;

  int? _userId;

  String? _crmId;

  String? _token;

  RDApi(this.host, this.version, this.debug) {
    _httpService.setCommon(v: version, debug: debug);
  }

  void update(RouteSettings settings) {
    try {
      var map = settings.arguments as Map<String, dynamic>;
      _orgId = map["orgId"];
      _projectId = map["projectId"];
      _userId = map["userId"];
      _crmId = map["crmId"];
      _token = map["token"];
      _httpService.setTokenAndCrmId(token: _token!, crmId: _crmId!);
      _httpService.setHeaderId(orgId: _orgId!, projectId: _projectId!, userId: _userId!);
    } catch (e) {
      print(e);
    }
  }

  RDApi setTokenAndCrmId({required String token, required String crmId}) {
    _crmId = crmId;
    _token = token;
    _httpService.setTokenAndCrmId(token: _token!, crmId: _crmId!);
    return this;
  }

  RDApi setHeaderId({required int orgId, required int projectId, required int userId}) {
    _orgId = orgId;
    _projectId = projectId;
    _userId = userId;
    _httpService.setHeaderId(orgId: _orgId!, projectId: _projectId!, userId: _userId!);
    return this;
  }

  @override
  String toString() {
    return 'RDApi{_httpService: $_httpService, host: $host, version: $version, debug: $debug, _orgId: $_orgId, _projectId: $_projectId, _userId: $_userId, _token: $_token, _crmId: $_crmId}';
  }

  Future<RDResponse> getRSAKey() async {
    String url = "${host}app/sys/getRSAKey";
    return await _httpService.post(url);
  }

  void getRSAKeyBy(void Function(String data) onData, {RDOnError? onError}) async {
    String url = "${host}app/sys/getRSAKeyasdasdasd";
    _httpService.post(url).then((value) {
      onData.call(value.data.toString());
    }, onError: (error) {
      onError?.onError(error);
    });
  }

  Future<RDResponse> loginByPassword(String account, String password, String key) async {
    return await _httpService.post(
      "${host}app/sys/login",
      body: {
        "data": {"password": password, "publicKey": key, "username": account},
        "loginType": Contact.deviceType
      },
      willRequest: () {
        Fluttertoast.showToast(msg: "开始请求");
      },
    );
  }
}
